<?php

namespace app\admin\logic;

use app\admin\validate\RoleValidate;
use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\RoleMenuService;
use support\Service\RoleService;

class RoleLogic extends BackendLogic
{

    private  $roleMenuService;

    public function __construct()
    {
       $this->service =Container::get(RoleService::class);
       $this->roleMenuService=Container::get(RoleMenuService::class);
       $this->validate= new RoleValidate();
    }

    /**
     * 角色列表(分页)
     * @return array
     */
    public  function getList(): array
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (!empty($param['name'])) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        $list = $this->service->getListPage($where);
        return message($list);
    }

    /**
     * 删除角色
     * @return array
     */
    public  function delete(): array
    {
        $ids = request()->post('id');
        if (!$ids) throw new ApiException('记录ID不能为空');
        if (!is_array($ids)) $ids = [$ids];
        if (in_array(1, $ids)) throw new ApiException('超级角色不能删除');
        $this->service->delete($ids);
        return message([], 20000, '删除成功');
    }

    /**
     * 角色列表
     * @return array
     */
    public  function getRoleList()
    {
        $list = $this->service->getRoleList();
        return message($list);
    }

    /**
     * 权限列表
     * @return array
     */
    public  function getPermissionList($role_id)
    {
        if (!$role_id) return message();
        $list = $this->service->getPermissionList($role_id);
        $list = createTreeList(0, $list);
        return message($list);
    }

    /**
     * 更改权限
     * @return array
     */
    public  function savePermission()
    {
        // 请求参数
        $roleId = request()->post('role_id', 0);
        $menuIds = request()->post('menu_id', []);
        if (!$roleId)  throw new ApiException('角色ID不能为空');
        // 插入角色菜单关系数据
        $menuIds = is_array($menuIds) ? $menuIds : [];
        // 删除角色菜单关系数据
        $this->roleMenuService->delete($roleId);
        if (!$menuIds) return message();
        $list = [];
        foreach ($menuIds as $val) {
            $data = [
                'role_id' => $roleId,
                'menu_id' => $val,
            ];
            $list[] = $data;
        }
        $this->roleMenuService->insertBatch($list);
        return message();

    }


}
